package com.palmind.util;

import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotOpenException;

/**
 * <p>
 * <code>RMSUtil</code>类对常用的RMS操作进行了封装。
 * </p>
 * <p>
 * The class <code>RMSUtil</code> encapsulates the general functions on RMS.
 * </p>
 * 
 * @author Jarod Yv
 */
public class RMSUtil {
	private RecordStore rs = null;// RecordStore

	private String rmsName = null;

	public RMSUtil(String rmsName) {
		this.rmsName = rmsName;
		openRms(rmsName);
	}

	public void openRms(String rmsName) {
		try {
			rs = RecordStore.openRecordStore(rmsName, true);
		} catch (RecordStoreException ex) {
		}
	}

	public int getRecordNums() {
		if (rs == null) {
			return 0;
		}
		try {
			int nums = rs.getNumRecords();
			return nums;
		} catch (RecordStoreNotOpenException ex) {
			return 0;
		}
	}

	public void delectRecord(int id) {
		int nums = getRecordNums();
		if (id < 1 || id > nums) {
			return;
		}
		try {
			rs.deleteRecord(id);
		} catch (RecordStoreNotOpenException e) {
		} catch (InvalidRecordIDException e) {
		} catch (RecordStoreException e) {
		}
	}

	public void addRecord(byte[] data) {
		int len = 0;
		if (data == null) {
			len = 0;
		} else {
			len = data.length;
		}
		try {
			rs.addRecord(data, 0, len);
		} catch (RecordStoreNotOpenException ex) {
		} catch (RecordStoreException ex) {
		}
	}

	public byte[] getRecode(int id) {
		byte[] dataByte = null;
		try {
			dataByte = rs.getRecord(id);
		} catch (InvalidRecordIDException ex) {
		} catch (RecordStoreNotOpenException ex) {
		} catch (RecordStoreException ex) {
		}
		return dataByte;
	}

	public void deleteRMS() {
		close();
		try {
			RecordStore.deleteRecordStore(rmsName);
		} catch (RecordStoreException ex1) {
		}
	}

	public void close() {
		try {
			if (rs != null) {
				rs.closeRecordStore();
				rs = null;
			}
		} catch (RecordStoreNotOpenException ex) {
		} catch (RecordStoreException ex) {
		}
	}
}
